package algorithm.beforestart;

import java.util.Arrays;
import java.util.HashMap;

public class majorityElement {
    public static int majorityElement(int[] nums) {
        int halfnum = nums.length / 2;
        HashMap<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < nums.length; i++) {
            if (map.containsKey(nums[i])) {
                int value = map.get(nums[i]);
                map.put(nums[i], ++value);
            } else {
                map.put(nums[i], 1);
            }
        }

        int result = 0;
        for (int key : map.keySet()) {
            int value = map.get(key);
            if (value > halfnum) {
                result = key;

            }
        }

        System.out.println(result);
        return result;

    }

    public static int majorityElement_better(int[] nums) {
        Arrays.sort(nums);
        return nums[nums.length / 2];
    }


    public static void main(String[] args) {
        int[] nums = {3, 2, 3};
//        majorityElement(nums);
        System.out.println(majorityElement_better(nums)
        );
    }
}
